from django.shortcuts import render, HttpResponse
from rest_framework import viewsets
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework.reverse import reverse

from django_filters.rest_framework import DjangoFilterBackend

from iClouds.Permissions import AllPermissions, MyPermissions
from iClouds.Authentication import MyJWTAuthentication

# from iClouds.mktoken import get_tokens_for_user
# from iClouds.apidev import filter_views, has_Random

from . import apidev as PAY
from .allinpayAPI import PAYAPI
from .serializers import *
from .serializersV2 import *
from mysqldb.serializers import ListDjangoFilterBackend

# from mysqldb import sems as SEMS


# Create your views here.
# 创建日志对象
import logging

logger = logging.getLogger("allinpay")


class paycode(viewsets.ModelViewSet):
    __title__ = "动态收款码页面"
    __doc__ = """
    list:\n
    <h4>主扫动态收款码页面</h4>
    `该接口禁用`
    read:\n
    <h4>创建动态收款码页面</h4>
    `该接口仅供接口测试使用`
    """

    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None
    schema = None

    def retrieve(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        # 读取缓存
        req = REDIS.redis_get("allinpay", pk)
        # if not req: return Response({"rescode": 400, "resmsg": {"allinpay": "订单已失效"}})
        print(req)
        return render(request, "allinpay/codepay.html", {"sess": req})

    def list(self, request):
        return Response({"rescode": 200, "resmsg": "不支持的接口"})


class ActivePayViewSet(viewsets.ModelViewSet):
    __title__ = "用户主扫收款"
    __doc__ = """
    create:\n
    <h4>用户主扫收款</h4>
    `系统出示动态收款码，用户扫码付款`\n
    返回数据: \n
        trxid 交易单号
        chnltrxid 渠道平台交易单号
        reqsn 商户交易单号
        randomstr 随机字符串
        trxstatus 交易状态
        fintime 交易完成时间
        errmsg 错误原因
        payinfo 支付串
    注: 该接口需要调用 `/loan/transquery/` 接口轮询结果。\n
    """

    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = ActivePaySerializer
    queryset = None

    def create(self, request):
        # 创建日志
        # PAY.writeLog({'act':'主扫请求','data':request.data})

        # 序列化请求字段
        serializer = ActivePaySerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 写入预收单缓存,防止重复提交
        REDIS.redis_put("bankreqsn", serializer.data["reqsn"], serializer.data, 60 * 30)

        # 清除自定义字段
        req = serializer.data.copy()
        pid = req.pop("pid")
        tid = req.pop("tid")
        pay = req.get("paytype")
        atm = req.get("trxamt")
        # req = {'reqsn': 'TY202212271116321', 'trxamt': 1, 'paytype': 'W01'}

        # 请求并返回数据
        sess = PAY.form_dict_format_post(req, "pays")
        # 原始返回数据
        # sess = {
        #     "appid": "00249015",
        #     "cusid": "660134048160C0S",
        #     "payinfo": "https://syb.allinpay.com/apiweb/h5unionpay/native?key=Ffc6CsYuLI%2FfGgMmH4DwWR6I",
        #     "randomstr": "216279600970",
        #     "reqsn": "TY202212271410124",
        #     "retcode": "SUCCESS",
        #     "trxid": "221227117549324619",
        #     "trxstatus": "0000",
        # }
        if sess.get("retcode") == "SUCCESS":
            del sess["cusid"]
            del sess["appid"]
            del sess["randomstr"]
            # return Response(sess)
            try:
                sess["placeid"] = AllinpayPlaceList.objects.get(id=pid).basename
            except BaseException as err:
                raise serializers.ValidationError({"placeid": "获取场所失败"})
            try:
                sess["termsn"] = AllinpayTermList.objects.get(id=tid).name
            except BaseException as err:
                raise serializers.ValidationError({"placeid": "获取经营名目失败"})
            # 支付方式
            sess["paytype"] = pay
            # 实际金额
            sess["trxamt"] = str(int(atm) / 100)
            # 测试页面地址
            sess["url"] = reverse(
                viewname="payapi:00扫码页面-detail", args=[sess["reqsn"]], request=request
            )
            # sess['url'] = reverse('payapi:paycode-detail', args=[sess['reqsn']], request=request)
            # sess['url'] = reverse('payapi:paycode', args=[sess['reqsn']], request=request)
            # sess["url"] = f'/loan/paycode/{sess["reqsn"]}/'
            # 写主扫缓存
            REDIS.redis_put("allinpay", sess["reqsn"], sess, 60 * 5)
            # 返回数据示例
            # {
            #     "payinfo": "https://syb.allinpay.com/apiweb/h5unionpay/native?key=lwShMdtVoFEOvgO12HYWUOo%2B",
            #     "reqsn": "TY202212271116326",
            #     "retcode": "SUCCESS",
            #     "trxid": "221227115949300092",
            #     "trxstatus": "0000",
            #     "placeid": "测试0",
            #     "termsn": "网费营收",
            #     "paytype": "W01",
            #     "trxamt": "0.01",
            #     "url": "/loan/paycode/TY202212271116326/",
            # }
        return Response({"rescode": 200, "resmsg": sess})


class SweptPayViewSet(viewsets.ModelViewSet):
    __title__ = "用户被扫收款"
    __doc__ = """
    create:\n
    <h4>用户被扫收款</h4>
    `用户出示动态付款码，系统扫码收款`\n

    返回数据: \n
        trxid 交易单号
        chnltrxid 渠道平台交易单号
        reqsn 商户交易单号
        trxstatus 交易状态
        acct 支付平台用户标识
        trxcode 交易类型
        fintime 交易完成时间
        errmsg 错误原因
        initamt 原交易金额
        trxamt 实际交易金额
        fee 手续费
        cmid 渠道子商户号
        chnlid 渠道号
        chnldata 渠道信息
        accttype 借贷标识
    注: 该接口需要调用 `/loan/transquery/` 接口轮询结果。  \n
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = SweptPaySerializer
    queryset = None

    def create(self, request):
        # 序列化请求字段
        serializer = SweptPaySerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 写入预收单缓存,防止重复提交
        REDIS.redis_put("bankreqsn", serializer.data["reqsn"], serializer.data, 60 * 30)

        # 清除自定义字段
        req = serializer.data.copy()
        pid = req.pop("pid")
        tid = req.pop("tid")
        atm = req.get("trxamt")

        # 请求并返回数据
        sess = PAY.form_dict_format_post(req, "scan")
        # 原始返回数据
        # sess = {
        #     "acct": "2088002473282723",
        #     "accttype": "99",
        #     "appid": "00249015",
        #     "chnltrxid": "2022122722001482721442250897",
        #     "cmid": "2088710380260890",
        #     "cusid": "660134048160C0S",
        #     "fee": "0",
        #     "fintime": "20221227141547",
        #     "initamt": "1",
        #     "randomstr": "830944251285",
        #     "reqsn": "TY202212271401126",
        #     "retcode": "SUCCESS",
        #     "trxamt": "1",
        #     "trxcode": "VSP511",
        #     "trxid": "221227114449316388",
        #     "trxstatus": "0000",
        # }
        if sess.get("retcode") == "SUCCESS":
            del sess["cusid"]
            del sess["appid"]
            del sess["randomstr"]
            return Response({"rescode": 200, "resmsg": sess})
        else:
            raise serializers.ValidationError(sess)


class TransQueryViewSet(viewsets.ModelViewSet):
    __title__ = "交易查询"
    __doc__ = """
    create:\n
    <h4>交易查询</h4>
    根据`reqsn`或`trxid`查询交易状态。\n
    返回数据: \n
        "acct":  支付平台用户标识,
        "accttype": 借贷标识,
        "chnltrxid": 渠道流水号,
        "cmid":      渠道子商户号,
        "fee":       手续费,
        "fintime":   交易完成时间,
        "initamt":   原交易金额,
        "reqsn":     商户订单号,
        "retcode":   返回码,
        "trxamt":    交易金额,
        "trxcode":   交易类型,
        "trxid":     交易单号,
        "trxstatus": 交易状态,
        "code":      状态码,
        "detail":    状态消息
    `注: 必须一个请求参数，二选一。`
    """

    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = TransQuerySerializer
    queryset = None

    def create(self, request):
        # 序列化请求字段
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 业务请求并返回数据
        sess = PAY.form_dict_format_post(serializer.data, "query")
        # 原始返回数据
        # sess = {
        #     "acct": "2088002473282723",
        #     "accttype": "99",
        #     "chnltrxid": "2022122722001482721441892467",
        #     "cmid": "2088710380260890",
        #     "fee": "0",
        #     "fintime": "20221227145141",
        #     "initamt": "1",
        #     "reqsn": "TY20221227145000123",
        #     "retcode": "SUCCESS",
        #     "trxamt": "1",
        #     "trxcode": "VSP511",
        #     "trxid": "221227116849312194",
        #     "trxstatus": "0000",
        # }
        if sess.get("retcode") == "SUCCESS":
            del sess["cusid"]
            del sess["appid"]
            del sess["randomstr"]
            return Response({"rescode": 200, "resmsg": sess})
        else:
            raise serializers.ValidationError(sess)


class alert(viewsets.ModelViewSet):
    __title__ = "消息通知"
    __doc__ = """
    create:\n
    <h4>接收通知消息</h4>
        通知频率为15s/15s/5m/10m/15m - 总计30m30s
        对于差错的交易,在通联平台跟渠道对账完毕(一般T+1),与商户之间的差错处理会补发通知,包含下面这两种情况：
        差错借记调整（VSP907）:通联向商户追差错款(补扣)
        差错贷记调整（VSP908）:通联将差错款清算给商户
        对于退款给持卡人的交易,并不会触发上述通知

        例如场景：持卡人T日交易时扣款成功了,但是通联平台交易失败.到了T+1日,通联对账后发现了这笔差错,通联运营人员跟商户进行沟通,商量结果是由通联把钱先清算给商户,由商户补发货给持卡人或者退款给持卡人,这样就触发了一笔贷记调整
    `内置系统接口，禁止用户调用。`
    """

    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AlertSerializer
    queryset = AllinpayReceiptList.objects.all()

    def create(self, request, *args, **kwargs):
        # 验证签名
        PAY.RSA_design(dict(request.data))
        # 序列化数据
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # 取预存参数对象
        res = REDIS.redis_get("bankreqsn", serializer.data["cusorderid"]) or {}
        # 原始数据
        # sess = {
        #     "acct": "2088002473282723",
        #     "accttype": "99",
        #     "appid": "00249015",
        #     "chnltrxid": "2022122822001482721449984834",
        #     "cmid": "2088710380260890",
        #     "cusid": "660134048160C0S",
        #     "cusorderid": "TY20221228111900123",
        #     "fee": "0",
        #     "initamt": "1",
        #     "outtrxid": "TY20221228111900123",
        #     "paytime": "20221228112011",
        #     "sign": "bEwW5iBn8h3nPsIvnkKEIIkF1c4r43Jo+Z9nCUraWaJZH9KgDgSbeTw+jSCSaDdjdgg+QfazAfMPXgXL+1dkcQEDmO0kz5cDQxZHasAWRc5qSuQkE15bTorNz6VRlXWIzk1ueoqSUGxRvWJO1Mv7BvuP7F8GK6Ra0fpQ2B3LbJU=",
        #     "signtype": "RSA",
        #     "termauthno": "221228118949376288",
        #     "termrefnum": "2022122822001482721449984834",
        #     "termtraceno": "0",
        #     "trxamt": "1",
        #     "trxcode": "VSP511",
        #     "trxdate": "20221228",
        #     "trxid": "221228118949376288",
        #     "trxstatus": "0000",
        # }
        # 创建数据
        sess = dict(serializer.data)
        sess["pid"] = res.get("pid", 0)
        sess["tid"] = res.get("tid", 0)
        cusorderid = sess.pop("cusorderid")
        # 创建日志
        logger.info(sess)
        # 更新数据库
        sess, faq = AllinpayReceiptList.objects.update_or_create(
            defaults=sess, cusorderid=cusorderid
        )

        return HttpResponse("success")


class CancelOrderViewSet(viewsets.ModelViewSet):
    __title__ = "撤销交易"
    __doc__ = """
    create:\n
    <h4>撤销交易</h4>
    返回数据: \n
        trxid 	交易单号
        reqsn 	商户订单号
        trxstatus 	交易状态
        fintime 	交易完成时间
        errmsg 	错误原因
        trxcode	交易类型
    注: 该接口直接返回结果，无需轮询.
    `只能撤销当天的交易，全额退款，实时返回退款结果`\n
    """

    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = CancelOrderSerializer
    queryset = None

    def create(self, request):
        # 序列化请求字段
        serializer = CancelOrderSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 写入预收单缓存,防止重复提交
        REDIS.redis_put("bankreqsn", serializer.data["reqsn"], serializer.data, 60 * 30)
        # 清除自定义字段
        req = serializer.data.copy()
        pid = req.pop("pid")
        tid = req.pop("tid")
        # 业务请求并返回数据
        sess = PAY.form_dict_format_post(req, "cancel")
        # 原始数据
        # sess = {
        #     "fintime": "20221228131742",
        #     "reqsn": "TY20221228131700123",
        #     "retcode": "SUCCESS",
        #     "trxcode": "VSP512",
        #     "trxid": "221228116949376048",
        #     "trxstatus": "0000",
        # }
        if sess.get("retcode") == "SUCCESS":
            del sess["cusid"]
            del sess["appid"]
            del sess["randomstr"]
            if sess.get("trxstatus") == "0000":
                sess["pid"] = pid
                sess["tid"] = tid
                serializer = AllOrderSerializer(data=sess)
                serializer.is_valid(raise_exception=True)
                trxid = sess.pop("trxid")
                obj, faq = AllinpayCancelList.objects.update_or_create(
                    defaults=sess, trxid=trxid
                )
                return Response({"rescode": 200, "resmsg": obj})

        raise serializers.ValidationError(sess)


class ReturnOrderViewSet(viewsets.ModelViewSet):
    __title__ = "退款交易"
    __doc__ = """
    create:\n
    <h4>退款交易</h4>
    返回数据: \n
        trxid 	交易单号
        reqsn 	商户订单号
        trxstatus 	交易状态
        fintime 	交易完成时间
        errmsg 	错误原因
        fee 	手续费
        trxcode 	交易类型
        chnltrxid 	渠道流水号
    `支持部分金额退款，隔天交易退款。（建议在交易完成后间隔几分钟（最短5分钟）再调用退款接口，避免出现订单状态同步不及时导致退款失败。）含单品优惠交易只能整单退款，不支持部分退款.`\n
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = ReturnOrderSerializer
    queryset = None

    def create(self, request):
        # 序列化请求字段
        serializer = CancelOrderSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 写入预收单缓存,防止重复提交
        REDIS.redis_put("bankreqsn", serializer.data["reqsn"], serializer.data, 60 * 30)
        # 清除自定义字段
        req = serializer.data.copy()
        pid = req.pop("pid")
        tid = req.pop("tid")
        # 业务请求并返回数据
        sess = PAY.form_dict_format_post(req, "refund")
        # print(sess)
        # 原始数据
        # sess = {
        #     "errmsg": "此交易不允许进行退货处理",
        #     "fintime": "20221228132456",
        #     "reqsn": "TY20221228132400123",
        #     "retcode": "SUCCESS",
        #     "trxcode": "VSP503",
        #     "trxstatus": "3999",
        # }
        if sess.get("retcode") == "SUCCESS":
            del sess["cusid"]
            del sess["appid"]
            del sess["randomstr"]
            if sess.get("trxstatus") == "0000":
                sess["pid"] = pid
                sess["tid"] = tid
                serializer = AllOrderSerializer(data=sess)
                serializer.is_valid(raise_exception=True)
                trxid = sess.pop("trxid")
                obj, faq = AllinpayCancelList.objects.update_or_create(
                    defaults=sess, trxid=trxid
                )
                return Response({"rescode": 200, "resmsg": obj})

        raise serializers.ValidationError(sess)


# ===================================================================
class ActivePayViewSetV2(viewsets.ModelViewSet):
    __title__ = "用户主扫收款V2"
    __doc__ = """
    create:\n
    <h4>用户主扫收款</h4>
    `系统出示动态收款码，用户扫码付款`\n
    注: 该接口需要调用 `/loan/transquery/` 接口轮询结果。\n
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = ActivePaySerializerV2
    queryset = None

    def create(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 创建新的对象
        sess = serializer.data.copy()
        # 提取商户原始凭证
        order = serializer.data["reqsn"]
        # 创建平台唯一收单凭证
        sess["reqsn"] = PAY.has_reqsn()
        sess["order"] = order
        # 写入预收单缓存,防止重复提交
        REDIS.redis_hash_set("bankreqsn", sess["reqsn"], sess, 60 * 30)
        # 准备数据
        data = {
            "reqsn": sess["reqsn"],
            "paytype": sess["paytype"],
            "trxamt": sess["trxamt"],
            "remark": order,
        }
        # 同步请求
        res = PAYAPI.to_format_data("pays", data=data)
        if not res:
            return Response(
                {
                    "rescode": 400,
                    "resmsg": {
                        "reqsn": sess["reqsn"],
                        "order": order,
                        "message": "请求错误",
                    },
                }
            )

        # 创建用户数据
        res["paytype"] = sess["paytype"]
        res["trxamt"] = sess["trxamt"]
        res["order"] = order
        res["pid"] = sess["pid"]
        res["tid"] = sess["tid"]
        try:
            res["placeid"] = AllinpayPlaceList.objects.get(id=sess["pid"]).basename
        except BaseException as err:
            res["placeid"] = ""
        try:
            res["termsn"] = AllinpayTermList.objects.get(id=sess["tid"]).name
        except BaseException as err:
            res["termsn"] = ""
        # 写主扫缓存
        REDIS.redis_hash_set("allinpay", res["reqsn"], res, 60 * 30)
        # 创建反向路由
        res["url"] = reverse(
            viewname="payapi:00扫码页面-detail", args=[res["reqsn"]], request=request
        )
        return Response({"rescode": 200, "resmsg": res})


class SweptPayViewSetV2(viewsets.ModelViewSet):
    __title__ = "用户被扫收款"
    __doc__ = """
    create:\n
    <h4>用户被扫收款</h4>
    `用户出示动态付款码，系统扫码收款`\n

    返回数据: \n
        trxid 交易单号
        chnltrxid 渠道平台交易单号
        reqsn 商户交易单号
        trxstatus 交易状态
        acct 支付平台用户标识
        trxcode 交易类型
        fintime 交易完成时间
        errmsg 错误原因
        initamt 原交易金额
        trxamt 实际交易金额
        fee 手续费
        cmid 渠道子商户号
        chnlid 渠道号
        chnldata 渠道信息
        accttype 借贷标识
    注: 该接口需要调用 `/loan/transquery/` 接口轮询结果。  \n
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = SweptPaySerializerV2
    queryset = None

    def create(self, request):
        # 序列化请求字段
        serializer = SweptPaySerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 创建新的对象
        sess = serializer.data.copy()
        # 提取商户原始凭证
        order = serializer.data["reqsn"]
        # 创建平台唯一收单凭证
        sess["reqsn"] = PAY.has_reqsn()
        sess["order"] = order
        # 写入预收单缓存,防止重复提交
        REDIS.redis_hash_set("bankreqsn", sess["reqsn"], sess, 60 * 30)
        # 准备数据
        data = {
            "reqsn": sess["reqsn"],
            "trxamt": sess["trxamt"],
            "remark": order,
            "authcode": sess["authcode"],
        }

        # 同步请求
        res = PAYAPI.to_format_data("scan", data=data)
        if not res:
            return Response(
                {
                    "rescode": 400,
                    "resmsg": {
                        "reqsn": sess["reqsn"],
                        "order": order,
                        "message": "请求错误",
                    },
                }
            )
        # print(res)
        # 原始单号
        res["order"] = order
        return Response({"rescode": 200, "resmsg": res})


class alertV2(viewsets.ModelViewSet):
    __title__ = "消息通知"
    __doc__ = """
    create:\n
    <h4>接收通知消息</h4>
        通知频率为15s/15s/5m/10m/15m - 总计30m30s
        对于差错的交易,在通联平台跟渠道对账完毕(一般T+1),与商户之间的差错处理会补发通知,包含下面这两种情况：
        差错借记调整（VSP907）:通联向商户追差错款(补扣)
        差错贷记调整（VSP908）:通联将差错款清算给商户
        对于退款给持卡人的交易,并不会触发上述通知

        例如场景：持卡人T日交易时扣款成功了,但是通联平台交易失败.到了T+1日,通联对账后发现了这笔差错,通联运营人员跟商户进行沟通,商量结果是由通联把钱先清算给商户,由商户补发货给持卡人或者退款给持卡人,这样就触发了一笔贷记调整
    `内置系统接口，禁止用户调用。`
    """

    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AlertSerializerV2
    queryset = None

    def create(self, request, *args, **kwargs):
        # 序列化数据
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 验签
        c = PAYAPI.has_conf()
        s = PAYAPI.RSA_design(c.get("bnkpublic"), serializer.data)
        if not s:
            return HttpResponse("falt")

        # 创建新的对象
        sess = serializer.data.copy()

        # print(sess)
        # 取预存参数对象
        res = REDIS.redis_hash_has("bankreqsn", sess.get("cusorderid"))
        if not res:
            return HttpResponse("falt")
        sess["pid"] = res.get("pid")
        sess["tid"] = res.get("tid")
        sess["order"] = res.get("order")
        cusorderid = sess.pop("cusorderid")

        # 更新数据库
        req, faq = AllinpayReceiptList.objects.update_or_create(
            defaults=sess, cusorderid=cusorderid
        )
        return HttpResponse("success")


class PaycodeManualPage(viewsets.ModelViewSet):
    __title__ = "手动支付测试页面"
    __doc__ = """
    list:\n
    <h4>手动支付测试页面</h4>
    `该接口仅供接口测试使用`
    read:\n
    <h4>手动支付测试页面</h4>
    `该接口仅供接口测试使用`
    """

    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None
    schema = None

    def list(self, request, *args, **kwargs):
        return Response({"rescode": 200, "resmsg": "不支持的接口"})

    def retrieve(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        try:
            pid = AllinpayPlaceList.objects.get(id=pk, status=1)
            tid = AllinpayTermList.objects.filter(pid=pid.id, status=1).values(
                "id", "name"
            )
        except BaseException as err:
            return Response({"rescode": 504, "resmsg": "场所错误"})
        reqsn = PAY.has_reqsn()[2:]
        return render(
            request,
            "allinpay/ActiveCode.html",
            {"pid": pid.id, "tid": tid, "reqsn": reqsn},
        )


class PlaceStoredReqsnViewSet(viewsets.ModelViewSet):
    __title__ = "场所储值订单"
    __group__ = "视图类型"
    __info__ = {
        "get": "场所储值订单查询",
        "post": "场所储值订单创建",
        "put": "场所储值订单编辑",
        "delete": "场所储值订单移除",
    }
    __doc__ = """	list:
    <h4>场所储值订单列表</h4>
    retrieve:
    <h4>场所储值订单详情</h4>
    create:
    <h4>场所储值订单创建</h4>
    update:
    <h4>场所储值订单编辑</h4>
    delete:
    <h4>场所储值订单移除</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = PlaceStoredReqsnSerializer
    queryset = AllinpayPlacestoredReqsn.objects.all()

    # filter_backends = [ListDjangoFilterBackend]
    # filterset_fields = ['pid', 'intetype']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(reqsn=PAY.has_reqsn(), currentime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})


class PlaceStoredPayViewSet(viewsets.ModelViewSet):
    __title__ = "场所储值支付"
    __group__ = "视图类型"
    __info__ = {"get": "场所储值查询", "post": "场所储值创建", "put": "场所储值编辑", "delete": "场所储值移除"}
    __doc__ = """	list:
    <h4>场所储值列表</h4>
    retrieve:
    <h4>场所储值详情</h4>
    create:
    <h4>场所储值创建</h4>
    update:
    <h4>场所储值编辑</h4>
    delete:
    <h4>场所储值移除</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = PlaceStoredPaySerializer
    queryset = None
    # filter_backends = [ListDjangoFilterBackend]
    # filterset_fields = ['pid', 'intetype']

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


# 检查视图
from iClouds.apidev import filter_views

filter_views(globals())
